import { Component, ViewChildren, ViewChild, QueryList, HostListener, ElementRef, Renderer2 } from '@angular/core';
import {
  Platform, Events, ModalController, ActionSheetController, PopoverController,
  IonRouterOutlet, MenuController, ToastController, LoadingController, AlertController,
  NavController
} from '@ionic/angular';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';
import { AndroidPermissions } from '@ionic-native/android-permissions/ngx';

import { GlobalService } from '@services/global.service';
import { UpdateService } from '@services/update.service';
import { NativeService } from '@services/native.service';

import { DataService } from '@services/data.service';
import { CacheService } from '@services/cache.service';

import { Router, NavigationEnd, NavigationStart } from '@angular/router';
import { forkJoin, Subscription } from 'rxjs';

import { CodePush, SyncStatus, InstallMode } from '@ionic-native/code-push/ngx';
import { DEBUG, CODE_PUSH_DEPLOYMENT_KEY } from './codepush.constants';
import { JPush } from '@jiguang-ionic/jpush/ngx';
import { AppUpdate } from '@ionic-native/app-update/ngx';
import { Network } from '@ionic-native/network/ngx';

declare var window;

@Component({
  selector: 'app-root',
  templateUrl: 'app.component.html'
})
export class AppComponent {
  backButtonPressed: boolean = false; // 用于判断返回键是否触发
  customBackActionSubscription: Subscription;
  url;
  hideNav = false;
  loading: any;
  alert: any;
  // pages: Array<{ title: string; component: any }>;
  lastTimeBackPress = 0;
  timePeriodToExit = 2000;
  @ViewChildren(IonRouterOutlet)
  routerOutlets: QueryList<IonRouterOutlet>;
  pack = { label: null };
  selectedTheme: String;
  interval;
  constructor(
    private platform: Platform,
    private splashScreen: SplashScreen,
    private statusBar: StatusBar,
    public global: GlobalService,
    public native: NativeService,
    public updateService: UpdateService,
    public dataservice: DataService,
    public cache: CacheService,
    public events: Events,
    public toastCtrl: ToastController,
    public modalCtrl: ModalController,
    private menuCtrl: MenuController,
    private actionSheetCtrl: ActionSheetController,
    private popoverCtrl: PopoverController,
    private router: Router,
    private loadingCtrl: LoadingController,
    private codePush: CodePush,
    private androidPermissions: AndroidPermissions,
    private alertController: AlertController,
    public navCtrl: NavController,
    public jpush: JPush,
    public appUpdate: AppUpdate,
    private el: ElementRef,
    private render: Renderer2,
    private network: Network
  ) {
    this.initializeApp();
  }

  async initializeApp() {
    this.platform.ready().then(() => {
      this.statusBar.overlaysWebView(true);
      this.updateService.getAppVersion();
      if (this.platform.is('android')) {
        this.androidPermissions.checkPermission(this.androidPermissions.PERMISSION.CAMERA).then(
          result => console.log('Has CAMERA permission?', result.hasPermission),
          err => this.androidPermissions.requestPermission(this.androidPermissions.PERMISSION.CAMERA)
        );
        this.androidPermissions.checkPermission(this.androidPermissions.PERMISSION.RECORD_AUDIO).then(
          result => console.log('Has RECORD_AUDIO permission?', result.hasPermission),
          err => this.androidPermissions.requestPermission(this.androidPermissions.PERMISSION.RECORD_AUDIO)
        );
        this.androidPermissions.requestPermissions([this.androidPermissions.PERMISSION.CAMERA,
        this.androidPermissions.PERMISSION.RECORD_AUDIO, this.androidPermissions.PERMISSION.WRITE_EXTERNAL_STORAGE]);

        //  监测app版本更新
        if (this.network.type !== "unknown" && this.network.type !== "none") {
          console.log('安卓更新');
          this.updateService.checkAppUpdate(false);
        }
      } else {
        if (this.network.type !== "unknown" && this.network.type !== "none") {
          console.log('非安卓更新');
          this.updateService.checkUpdate();
        }
      }
      // 代码热更新
      this.splashScreen.hide();
      this.native.initNativeService();
      this.native.listenJPushInfo();
      this.cache.clientToken.subscribe((res) => {
        if (!res) {
          this.statusBar.hide();
        }
      })
      this.initService();
    });

    this.events.subscribe('qrScanner:show', () => {
      this.hideNav = true;
    });
    this.events.subscribe('qrScanner:hide', () => {
      this.hideNav = false;
    });
  }

  initService() {
    this.cache.jpushstate = !this.cache.jpushstate ? '1' : this.cache.jpushstate;
    this.cache.voiceState = !this.cache.voiceState ? 'on' : this.cache.voiceState;
    this.cache.apiConfig.subscribe(data => {
      // 路径如有token则跳过登录
      const token = this.getQueryString('token')
      if (!data) {
        this.dataservice.getConfig().subscribe(val => {
          this.cache.apiConfig = val.data;
          if (token.data) {
            this.goToPage(token);
          } else {
            this.router.navigate(['Login']);
          }
        });
      } else {
        if (token) {
          this.goToPage(token);
        } else {
          this.login();
        }
      }
    });
  }
  // PC综合态势跳转
  goToPage(token) {
    const projectId = this.getQueryString('projectId').data, projectName = this.getQueryString('projectName').data;
    this.cache.currentProject = { projectId, projectName };
    this.cache.clientToken = token.data;
    let url
    const queryParams = {
      projectId,
      projectName,
      systemId: this.getQueryString('systemId').data,
      systemName: this.getQueryString('systemName').data,
      deviceSysId: null,
      deviceSysName: null,
      iconShow: false
    };
    const systemId = this.getQueryString('systemId')
    if (systemId.data === '5') {
      url = 'RoomLiftPage';
    } else if (systemId.data === '4') {
      url = 'RoomFirePage';
    } else if (systemId.data === '10') {
      url = 'ParkPage';
    } else {
      url = 'SystemPage';
      queryParams.deviceSysId = systemId.data;
      queryParams.deviceSysName = this.getQueryString('systemName').data
    }
    this.navCtrl.navigateForward(['tabs/home/' + url], {
      queryParams
    });
  }

  // 正则提取url关键字
  getQueryString(name) {
    const reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    const r = window.location.search.substr(1).match(reg);
    if (r !== null) { return JSON.parse(JSON.stringify({ data: decodeURI(r[2]) })); } return null;
  }


  /**
* 物理键返回事件
*/

  @HostListener('document:ionBackButton', ['$event'])
  private registerBackButtonAction($event: any) {
    $event.detail.register(100, async () => {
      try {
        const action = await this.actionSheetCtrl.getTop();
        if (action) {
          action.dismiss();
          return;
        }
        const popover = await this.popoverCtrl.getTop();
        if (popover) {
          console.log('popover', popover)
          popover.dismiss();
          return;
        }
        const modal = await this.modalCtrl.getTop();
        if (modal) {
          console.log('modal', modal)
          modal.dismiss();
          return;
        }
      } catch (error) {
      }

      console.log('当前所在路由', this.router.url);
      if (this.router.url === '/login' || this.router.url === '/tabs/home/indexOperation' || this.router.url === '/tabs/home/indexGroup' || this.router.url === '/tabs/home/indexProject' || this.router.url === '/tabs/alarm' || this.router.url === '/tabs/my') {
        if (this.backButtonPressed) {
          console.log('退出')
          this.backButtonPressed = false;
          navigator['app'].exitApp();
        } else {
          console.log('单击')
          this.toastCtrl
            .create({
              message: '再按一次退出应用',
              duration: 2000,
              position: 'top',
            }).then(toast => {
              toast.present();
            });
          this.backButtonPressed = true;
          setTimeout(() => (this.backButtonPressed = false), 2000);
        }
      } else {
        console.log('返回上一层');
        this.navCtrl.pop();
      }
    });
  }

  // // 返回事件
  // goBack() {
  //   console.log(this.url);
  //   if (this.url === '/login' || this.url === '/tabs/home/indexOperation' || this.url === '/tabs/home/indexGroup' || this.url === '/tabs/home/indexProject' || this.url === '/tabs/alarm' || this.url === '/tabs/my') {
  //     if (this.backButtonPressed) {
  //       console.log('退出')
  //       this.backButtonPressed = false;
  //       navigator['app'].exitApp();
  //     } else {
  //       console.log('单击')
  //       this.toastCtrl
  //         .create({
  //           message: '再按一次退出应用',
  //           duration: 2000,
  //           position: 'top',
  //         }).then(toast => {
  //           toast.present();
  //         });
  //       this.backButtonPressed = true;
  //       setTimeout(() => (this.backButtonPressed = false), 2000);
  //     }
  //   } else {
  //     console.log('返回上一层', this.url)
  //     this.navCtrl.pop();
  //   }
  // }

  // initRouterListen() {
  //   this.router.events.subscribe(event => { // 需要放到最后一个执行
  //     if (event instanceof NavigationEnd) {
  //       this.url = event.url;
  //     }
  //   });
  // }

  /**
  * 每次启动都进行登录
  */
  login() {
    this.statusBar.show();
    this.statusBar.overlaysWebView(true);
    if (this.cache.userinfo) {
      const user = {
        username: this.cache.userinfo.account,
        password: this.cache.upwd
      };
      this.cache.clientToken.subscribe((res) => {
        if (res) {
          this.global.isLogin = true;
          this.dataservice.setHeader();

          const userData = this.dataservice.getUserInfo();
          const functionData = this.dataservice.getFunctions(null);
          const companyData = this.dataservice.getCompanyInfo();

          forkJoin([userData, functionData, companyData]).subscribe(results => {
            const userdata: any = results[0];
            this.cache.functionPoint = results[1].data;
            if (userdata.success) {
              const result = JSON.parse(JSON.stringify(userdata.data));
              const userInfo = result;
              this.cache.userinfo = userInfo;
              this.cache.userinfo.password = this.cache.upwd;
              this.cache.companys = results[2].data;
              this.jupushInit();
              this.router.navigate(['/tabs/' + this.cache.getCurrentIndexPage()]);
            }
          });
        } else {
          this.router.navigate(['login']);
        }
      })
    } else {
      this.router.navigate(['login']);
    }
  }


  // 极光初始化服务
  jupushInit() {
    this.jpush.init();
    this.jpush.setDebugMode(true);
    if (!this.cache.jpushstate || this.cache.jpushstate === '1' || this.cache.jpushstate === '') {
      this.jpush.setAlias({
        sequence: new Date().getTime(),
        alias: this.cache.userinfo.userId.toString(),
      }).then((args) => {
        console.log('极光设置成功', args);
      }).catch(err => {
        console.log('极光设置失败', err);
        if (window.cordova) {
          this.jupushInit();
        }
      });
    }
  }

}
